/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.lijigou.shopping;



import com.connect.Kaixin;
import com.connect.KaixinDialogListener;
import com.connect.Util;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;


 

/**
 */
public class KaixinActivity extends Activity implements KaixinDialogListener{

	private static final float[] DIMENSIONS_LANDSCAPE = { 460, 260 };
	private static final String DIALOG_LOADING = "加载中请稍候..";
	private WebView webView = null;
	private ProgressBar progressBar = null;
	private String mUrl;
	private KaixinDialogListener mListener;
	private WebView mWebView;
	private ProgressDialog mProgress;
 

	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share);
		mUrl=Kaixin.url;
		showProgress();
		progressBar = (ProgressBar) this.findViewById(R.id.progressBar);
		mWebView = (WebView) this.findViewById(R.id.webview);
		
//		mContent = new LinearLayout(this);
//		mContent.setOrientation(LinearLayout.VERTICAL);
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setUpWebView();
//
//		Display display = getWindow().getWindowManager().getDefaultDisplay();
//		float scale = this.getResources().getDisplayMetrics().density;
//		float[] dimensions = display.getWidth() < display.getHeight() ? DIMENSIONS_PORTRAIT
//				: DIMENSIONS_LANDSCAPE;
//		Window window = this.getWindow();
//		window.setLayout(display.getWidth(), display.getHeight());
//
//		
//		addContentView(mContent, new FrameLayout.LayoutParams(
//				(int) (dimensions[0] * scale + 0.5f), (int) (dimensions[1]
//						* scale + 0.5f)));
	}

	private void setUpWebView() {
		setView();
		mWebView.loadUrl(mUrl);
//		FrameLayout.LayoutParams fill = new FrameLayout.LayoutParams(
//				ViewGroup.LayoutParams.FILL_PARENT,
//				ViewGroup.LayoutParams.FILL_PARENT);
//		mWebView.setLayoutParams(fill);
	}
	private void setView() {
		progressBar = (ProgressBar) this.findViewById(R.id.progressBar);
		webView = (WebView) this.findViewById(R.id.webview);
		WebSettings setting = webView.getSettings();
		setting.setBuiltInZoomControls(false);
		setting.setSupportZoom(false);
		setting.setJavaScriptEnabled(true);
		setting.setSupportMultipleWindows(false);
		setting.setLightTouchEnabled(true);
		webView.setBackgroundColor(0);
		webView.setHorizontalScrollBarEnabled(true);
		webView.setHorizontalScrollbarOverlay(true);
		webView.setVerticalScrollBarEnabled(true);
		webView.setVerticalScrollbarOverlay(true);
		webView.requestFocus();
		setting.setLoadWithOverviewMode(true);
		webView.getSettings().setJavaScriptEnabled(true);  



		webView.setWebViewClient(new WebViewClient() {
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if ("lookoo".equals(url.substring(0, 6))) {
					Uri uri = Uri.parse(url);
					startActivity(new Intent(Intent.ACTION_VIEW, uri));
					KaixinActivity.this.finish();
					return true;
				}
				return super.shouldOverrideUrlLoading(view, url);
			}
		});
		webView.setWebChromeClient(new WebChromeClient(){
			
			public void onProgressChanged(WebView view, int newProgress) {
				view.getProgress();
				if(newProgress==100){
					progressBar.setVisibility(View.GONE);
					hideProgress();
					
				}else{
					progressBar.setVisibility(View.VISIBLE);
					progressBar.setProgress(newProgress);
				}
				super.onProgressChanged(view, newProgress);
			}
		});
	}
	
	
	public int onPageBegin(String url) {
		return KaixinDialogListener.DIALOG_PROCCESS;
	}

	
	public void onPageFinished(String url) {
	}

	
	public boolean onPageStart(String url) {
		return (KaixinDialogListener.PROCCESSED == parseUrl(url));
	}

	
	public void onReceivedError(int errorCode, String description,
			String failingUrl) {
		Toast.makeText(KaixinActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
	}

	private int parseUrl(String url) {
		if (url.startsWith(Kaixin.KX_AUTHORIZE_CALLBACK_URL)) {
			Bundle values = Util.parseUrl(url);
			String error = values.getString("error");// ��Ȩ������صĴ������
			if (error != null) {
				if (Kaixin.ACCESS_DENIED.equalsIgnoreCase(error)) {
				} else if (Kaixin.LOGIN_DENIED.equalsIgnoreCase(error)) {
				} else {
					Toast.makeText(KaixinActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
				}

				Util.clearCookies(KaixinActivity.this);

				Kaixin.setAccessToken(null);
				Kaixin.setRefreshToken(null);
				Kaixin.setAccessExpires(0L);

			} else {
				this.authComplete(values, url);
			}
			return KaixinDialogListener.PROCCESSED;
		}
		return KaixinDialogListener.UNPROCCESS;
	}
	/**
	 * 显示等待框
	 * 
	 * @param title
	 * @param message
	 */
	protected void showProgress() {
		this.runOnUiThread(new Runnable() {
			public void run() {	
				mProgress = new ProgressDialog(KaixinActivity.this);
				mProgress.requestWindowFeature(Window.FEATURE_NO_TITLE);
				mProgress.setMessage("正在加载授权页面...");
				mProgress.show();
			}
		});
	}

	/**
	 * 取消等待框
	 */
	protected void hideProgress() {
		
		this.runOnUiThread(new Runnable() {
			public void run() {
				if (mProgress != null) {
					mProgress.dismiss();
				}
			}
		});
	}
	private void authComplete(Bundle values, String url) {
//		CookieSyncManager.getInstance().sync();
//		String accessToken = values.getString(Kaixin.ACCESS_TOKEN);
//		String refreshToken = values.getString(Kaixin.REFRESH_TOKEN);
//		String expiresIn = values.getString(Kaixin.EXPIRES_IN);
//		Log.i("accessToken", accessToken+"---save---"+refreshToken);
//		Long temp=Long.parseLong(expiresIn);
//		SharedPreferences sp = KaixinDialog.this.getSharedPreferences(Kaixin.KAIXIN_SDK_STORAGE,
//				Context.MODE_PRIVATE);
//		sp.edit().putString(Kaixin.KAIXIN_SDK_STORAGE_ACCESS_TOKEN, accessToken).commit();
//		sp.edit().putString(Kaixin.KAIXIN_SDK_STORAGE_REFRESH_TOKEN, refreshToken).commit();
//		sp.edit().putLong(Kaixin.KAIXIN_SDK_STORAGE_EXPIRES, temp).commit();
//		if (accessToken != null && refreshToken != null
//				&& expiresIn != null) {
//			try {
//				Kaixin.setAccessToken(accessToken);
//				Kaixin.setRefreshToken(refreshToken);
//				Kaixin.setAccessExpiresIn(expiresIn);
//				Intent result = new Intent();
//				result.setClassName(Constant.packageName, "com.kaixin.connect"
//						+ ".KaixinDialog");
//				startActivity(result);
//			} catch (Exception e) {
//				Toast.makeText(KaixinDialog.this, "登录失败", Toast.LENGTH_SHORT).show();
//			}
//		} else {
//			Toast.makeText(KaixinDialog.this, "登录失败", Toast.LENGTH_SHORT).show();
//		}
	}
}
	
